import ArticleItem from '@/components/ArticleItem';
import NavBar from '@/components/NavBar';
import {
  clearResultsAction,
  getSearchResultAction,
} from '@/store/action/scarch';
import { useAppSelector } from '@/store/reducer';
import { InfiniteScroll } from 'antd-mobile';
import { useEffect, useRef } from 'react';
import { useDispatch } from 'react-redux';
import { useLocation } from 'react-router-dom';
import styles from './index.module.scss';

export default function SearchResult(props: any) {
  console.log(props);
  // 获取动态路由传参
  // const params = useParams() as any;
  // console.log(params.q);

  // 获取路由传过来的参数
  // const { state } = useLocation();
  // const { keyWord } = state as any;
  // console.log(keyWord);

  // URLSearchParams原生方法 获取参数
  const { search } = useLocation();
  // console.log(search);
  const searchParams = new URLSearchParams(search);
  const keyWord = searchParams.get('q') as string;
  // console.log(keyWord);

  const dispatch = useDispatch();
  // useEffect(() => {
  //   // 发送请求
  //   dispatch(getSearchResultAction(keyWord));
  // }, [keyWord, dispatch]);

  // 取出搜索结果数据
  const { results } = useAppSelector((state) => state.scarch);
  // console.log(results);

  // 组件卸载时清除搜索结果数据
  useEffect(() => {
    return () => {
      dispatch(clearResultsAction());
    };
  }, [dispatch]);

  const pageRef = useRef(0);
  // 无限加载,上拉加载
  const handleloadMore = async () => {
    // console.log(123);
    pageRef.current += 1;
    await dispatch(getSearchResultAction(keyWord, pageRef.current));
  };

  // 页码数*每页显示条数,少于实际返回的总数,就继续加载
  const hasMore = pageRef.current * 10 <= results.length;

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar fixed>搜索结果</NavBar>

      <div className="article-list">
        {results.map((item) => (
          <ArticleItem key={item.art_id} data={item} />
        ))}
      </div>

      {/* 无限加载 */}
      <InfiniteScroll loadMore={handleloadMore} hasMore={hasMore} />
    </div>
  );
}
